from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from api.api_db import insert_fax_to_idrs, doc_df_to_review_tb
from common.pd import get_tb_data
from common.pyside2_table.qtable import Base_Table
from common.pyside2_table.qt_wgt import show_msg
from common.config import public_data
from view.common_fun import add_download_widget
from view.tab_widget import Header_Select_Layout, Header_search_Layout
from view.table_col_list import fax_col_model_list


class View_Fax(QWidget):
    def __init__(self):
        super().__init__()
        self.view_name = "tab_fax"
        self.data = public_data
        self.db_table_name = "fax_contract"
        self.setupUi()
        self.bind()

    def setupUi(self):
        # region 布局
        # 整体布局为垂直布局
        lt_pg = QVBoxLayout(self)
        fm_ctrl = QFrame()

        lt_pg.addWidget(fm_ctrl)
        lt_header = QHBoxLayout(fm_ctrl)

        # endregion

        # region 项目、制造厂及采购包选择
        self.lt_select = Header_Select_Layout(lt_header, self.cmb_change)
        self.lb_sender = QLabel("发送方")
        self.cmb_sender = QComboBox()
        self.lb_fax_type = QLabel("函件类型")
        self.cmb_fax_type = QComboBox()
        lt_header.addWidget(self.lb_sender)
        lt_header.addWidget(self.cmb_sender)
        lt_header.addWidget(self.lb_fax_type)
        lt_header.addWidget(self.cmb_fax_type)

        # 左侧项目cmb
        left_spacer = QSpacerItem(120, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        lt_header.addItem(left_spacer)

        # endregion

        # region 中间查询
        self.search_txt_ly = Header_search_Layout(lt_header)
        self.btn_once_search = QPushButton("once搜索")
        lt_header.addWidget(self.btn_once_search)

        # endregion
        self.tb_factory_doc = Base_Table(self.db_table_name, fax_col_model_list)
        add_download_widget(lt_header, self.tb_factory_doc, "fax")

        # region 操作DRCS和IDRS
        right_spacer = QSpacerItem(50, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.btn_add_drcs = QPushButton("答复此函")
        self.btn_add_idrs = QPushButton("发起协审")
        self.btn_reset = QPushButton("重置")

        lt_header.addItem(right_spacer)
        lt_header.addWidget(self.btn_add_drcs)
        lt_header.addWidget(self.btn_add_idrs)
        lt_header.addWidget(self.btn_reset)
        # endregion

        # region 信息展示标签和表格
        self.lb_message = QLabel(text="更新日期是：")
        self.lb_message.setAutoFillBackground(False)
        self.lb_message.setWordWrap(True)
        lt_pg.addWidget(self.lb_message, 0, Qt.AlignLeft)

        # 数据表

        self.tb_factory_doc.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tb_factory_doc.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置为行模式
        self.tb_factory_doc.setSelectionMode(QAbstractItemView.ExtendedSelection)  # 允许选择多个
        lt_pg.addWidget(self.tb_factory_doc)
        self.tb_factory_doc.reset_data()
        self.init_sender_and_type()

        # endregion

    def bind(self):
        """控件绑定信息"""
        self.search_txt_ly.btn_db_search.clicked.connect(self.search_local)
        self.btn_add_drcs.clicked.connect(lambda: self.add_to_review("fax_reply"))
        self.btn_add_idrs.clicked.connect(lambda: self.add_to_review("idrs"))
        self.btn_reset.clicked.connect(lambda: self.reset_page)
        self.cmb_fax_type.currentTextChanged.connect(self.cmb_change)
        self.cmb_sender.currentTextChanged.connect(self.cmb_change)

    def update_doc_view(self, condition):
        show_msg(f"已完成查询，共查新{2}条", "blue", self.lb_message)

    # region 查询表格信息
    def cmb_change(self):
        sql_str = self.get_cmb_sql_str()
        datas = get_tb_data(self.db_table_name, sql_str)
        self.tb_factory_doc.reset_data(datas)
        # self.dis_connected_cmb()

    def get_cmb_sql_str(self):
        select_status: dict = self.lt_select.get_change_status()
        sql_condition_list: list = []
        for key in select_status.keys():
            sql_condition_list.append(f'{key}= "{select_status[key]}"')
        sender_code = self.cmb_sender.currentText()
        fax_type = self.cmb_fax_type.currentText()
        if sender_code != "所有":
            if sender_code == "制造厂":
                str_sender = '(channel not like "%-L-GENS-%"  and  channel not like "%-L-GDNS-%" )'

                sql_condition_list.append(str_sender)
            if sender_code == "工程公司":
                sql_condition_list.append(f' channel like "%-L-GENS-%"')
            if sender_code == "设计方":
                sql_condition_list.append(f' channel like "%-L-GDNS-%"')
        if not fax_type or fax_type != "所有":
            sql_condition_list.append(f' fax_type like "%{fax_type}%"')
        return " and ".join(sql_condition_list)

    def add_to_tb(self, is_idrs=0):
        select_row_df = self.tb_factory_doc.get_selected_rows_df()
        doc_df_to_review_tb(select_row_df, is_idrs)

    def search_local(self):
        txt_search_str = self.search_txt_ly.get_search_txt_to_sql()
        if not txt_search_str:
            return
        datas = self.tb_factory_doc.datas
        row_count, col_count = datas.shape

        if row_count < 500:
            re_condition_str = ".*" + txt_search_str.replace("*", ".*") + ".*"
            df_find_data = datas[datas['look_up_str'].str.match(re_condition_str)]
            self.tb_factory_doc.show_data(df_find_data)
        else:
            txt_condition = "look_up_str like " + "'%" + txt_search_str.replace("*", "%") + "%'"
            cmd_sql_str = self.get_cmb_sql_str()
            if cmd_sql_str:
                sql_str = cmd_sql_str + " and " + txt_condition
            else:
                sql_str = txt_condition

            datas = get_tb_data(self.db_table_name, sql_str)
            self.tb_factory_doc.reset_data(datas)

    def init_sender_and_type(self, ):
        """设置 函件类型和发送放信息"""
        fax_type_list = ["所有", "一般信函", "澄清", "变更", "DEN", "NCR", "会议", "合同商务", "发货", "质量保证",
                         "发票", "接口", "文件传递", "审查"]
        sender_list = ["所有", "制造厂", "工程公司", "设计方"]
        self.cmb_fax_type.addItems(fax_type_list)
        self.cmb_sender.addItems(sender_list)

    # endregion

    def add_to_review(self, table_name):
        datas = self.tb_factory_doc.get_selected_rows()
        if datas.empty:
            QMessageBox.information(self, "函件选择", "没有选择函件，请核实", QMessageBox.Ok)
            return
        if table_name == "idrs":
                result = insert_fax_to_idrs(datas)
                if result["rst"]:
                    show_msg(result["msg"],"blue",lb_msg=self.lb_message)
                else:
                    show_msg(result["msg"], "red", lb_msg=self.lb_message)